<template>
  <div class="travel-route-container">
    <div class="header-section">
      <h2>{{ authStore.getCustomerName }}的旅行路线</h2>
      <p class="subtitle">查看您的完整旅行计划和预约信息</p>
    </div>

    <div class="controls">
      <button @click="fetchTravelRoute" class="primary-button">
        <span v-if="loading" class="button-loading">
          <i class="el-icon-loading"></i> 加载中...
        </span>
        <span v-else>查询旅行路线</span>
      </button>
      <el-button
          @click="handleBack"
          type="warning"
      >
        返回
      </el-button>
    </div>

    <div class="route-content">
      <div class="route-header">
        <p class="route-notice">点位位置与实际地理位置无关, 仅作为路线展示</p>
      </div>

      <div class="canvas-container">
        <canvas ref="routeCanvas" width="800" height="500"></canvas>
      </div>
    </div>

    <!-- 路径完整性检查部分 -->
    <div class="integrity-check-section">
      <h3>航班路线完整性检查</h3>
      <div class="check-controls">
        <div class="select-group">
          <label>出发城市:</label>
          <el-select v-model="startCity" placeholder="请选择出发城市" class="city-select">
            <el-option
                v-for="city in availableCities"
                :key="'start-'+city"
                :label="city"
                :value="city"
            />
          </el-select>
        </div>

        <div class="select-group">
          <label>目的城市:</label>
          <el-select v-model="endCity" placeholder="请选择目的城市" class="city-select">
            <el-option
                v-for="city in availableCities"
                :key="'end-'+city"
                :label="city"
                :value="city"
            />
          </el-select>
        </div>

        <button @click="checkRouteIntegrity" class="check-button">
          检查路径完整性
        </button>
      </div>

      <!-- 检查结果展示 -->
      <div v-if="checkResult !== null" class="check-result">
        <div v-if="checkResult.isComplete" class="result-success">
          <i class="el-icon-success"></i>
          <span>路径完整！您的航班路线可以从 {{ startCity }} 到达 {{ endCity }}</span>
          <div v-if="checkResult.path" class="path-details">
            <p>完整路径: {{ checkResult.path.join(' → ') }}</p>
          </div>
        </div>
        <div v-else class="result-failure">
          <i class="el-icon-error"></i>
          <span>路径不完整！无法从 {{ startCity }} 到达 {{ endCity }}</span>

          <div v-if="checkResult.path && checkResult.path.length > 0" class="reachable-info">
            <p>可达城市: {{ checkResult.path.join(', ') }}</p>
          </div>
        </div>
      </div>
    </div>

    <div class="cards-container">
      <el-row :gutter="30">
        <el-col :xs="24" :sm="12">
          <el-card class="info-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <i class="el-icon-tickets"></i>
                <span>航班预约信息</span>
              </div>
            </template>
            <div v-if="routeTransports.length > 0">
              <div v-for="rt in routeTransports" class="text item flight-item">
                <i class="el-icon-plane"></i>
                出发地 <span class="city-highlight">{{ rt.fromCity }}</span>
                →
                目的地 <span class="city-highlight">{{ rt.arivCity }}</span>
              </div>
            </div>
            <div v-else class="empty-state">
              <i class="el-icon-info"></i>
              <p>暂无航班预约信息</p>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12">
          <el-card class="info-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <i class="el-icon-office-building"></i>
                <span>酒店巴士预约信息</span>
              </div>
            </template>
            <div v-if="routePoints.length > 0">
              <div v-for="rp in routePoints" class="text item location-item">
                <div class="location-header">
                  <i class="el-icon-location"></i>
                  <span class="location-name">{{ rp.location }}</span>
                </div>
                <div class="reservation-status">
                  <span class="status-item">
                    <i class="el-icon-truck"></i> 巴士 {{ rp.isBusReserved ? '✅' : '❌' }}
                  </span>
                  <span class="status-item">
                    <i class="el-icon-house"></i> 酒店 {{ rp.isHotelReserved ? '✅' : '❌' }}
                  </span>
                </div>
              </div>
            </div>
            <div v-else class="empty-state">
              <i class="el-icon-info"></i>
              <p>暂无酒店巴士预约信息</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, computed } from 'vue'
import {
  type RoutePoint,
  type RouteTransport,
  type RoutePointCoordination
} from "../../types/DataTypes.ts";
import { useAuthStore } from "../../stores/authStore.ts";
import { api } from "../../api/Api.ts"
const authStore = useAuthStore();
import { useRouter } from "vue-router";
import {
  checkPathIntegrity,
  validateCitySelection,
  type PathCheckResult
} from './utils/pathIntegrityChecker.ts';

// 响应式数据
const routePoints = ref<RoutePoint[]>([]);
const routeTransports = ref<RouteTransport[]>([]);

const loading = ref(false)
const error = ref<string | null>(null)
const routeCanvas = ref<HTMLCanvasElement | null>(null)

onMounted(()=>{
  fetchTravelRoute();
})
// 返回
const router = useRouter();
const handleBack = () =>{
  router.push({name:'TravelReservation'})
}

// 方法
const fetchTravelRoute = async () => {
  loading.value = true
  error.value = null

  try {
    const response = await api.route.getCustomerTravelRoute(authStore.getCustomerName);
    if (response.success) {
      routePoints.value = (response.data as any).routePoints;
      routeTransports.value = (response.data as any).routeTransports;
    } else {
      ElMessage.warning(response.message);
    }
    nextTick(() => {
      drawRoute()
    })
  } catch (err: any) {
    console.error(err.message);
    ElMessage.error('获取旅行路线失败');
  } finally {
    loading.value = false
  }
}

const calculateCoordinates = (routePoints: RoutePoint[]): Record<string, RoutePointCoordination> => {
  const coordinates: Record<string, RoutePointCoordination> = {}
  const centerX = 400
  const centerY = 250
  const radius = 200

  // 将地点均匀分布在圆上
  routePoints.forEach((p, index) => {
    const angle = (index / routePoints.length) * 2 * Math.PI
    coordinates[p.location] = {
      routePoint: p,
      x: centerX + radius * Math.cos(angle),
      y: centerY + radius * Math.sin(angle),
    }
  })

  return coordinates
}

const drawArrow = (ctx: CanvasRenderingContext2D, fromX: number, fromY: number, toX: number, toY: number) => {
  const headLength = 15
  const dx = toX - fromX
  const dy = toY - fromY
  const angle = Math.atan2(dy, dx)

  // 箭头头部
  ctx.beginPath()
  ctx.moveTo(toX, toY)
  ctx.lineTo(toX - headLength * Math.cos(angle - Math.PI / 6), toY - headLength * Math.sin(angle - Math.PI / 6))
  ctx.moveTo(toX, toY)
  ctx.lineTo(toX - headLength * Math.cos(angle + Math.PI / 6), toY - headLength * Math.sin(angle + Math.PI / 6))
  ctx.stroke()
}

const drawConnections = (ctx: CanvasRenderingContext2D, coordinates: Record<string, RoutePointCoordination>) => {
  ctx.strokeStyle = '#f85f7b'
  ctx.lineWidth = 3
  ctx.setLineDash([])

  routeTransports.value.forEach(item => {
    const fromCoord = coordinates[item.fromCity]
    const toCoord = coordinates[item.arivCity]

    if (fromCoord && toCoord) {
      // 绘制连接线
      ctx.beginPath()
      ctx.moveTo(fromCoord.x, fromCoord.y)
      ctx.lineTo(toCoord.x, toCoord.y)
      ctx.stroke()

      // 绘制箭头
      drawArrow(ctx, fromCoord.x, fromCoord.y, toCoord.x, toCoord.y)
    }
  })
}

const drawLocationLabels = (ctx: CanvasRenderingContext2D, coordinates: Record<string, RoutePointCoordination>) => {
  ctx.font = 'bold 14px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'

  // 绘制地点点
  for (const [location, data] of Object.entries(coordinates)) {
    // 绘制圆点
    ctx.beginPath()
    ctx.arc(data.x, data.y, 8, 0, Math.PI * 2)
    ctx.fillStyle = '#409EFF'
    ctx.fill()
    ctx.strokeStyle = '#ffffff'
    ctx.lineWidth = 2
    ctx.stroke()

    // 绘制地点名称
    ctx.fillStyle = '#303133'
    ctx.fillText(location, data.x, data.y + 25)
  }
}

const drawRoute = () => {
  const canvas = routeCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  if (!ctx) return

  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 设置渐变背景
  const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)
  gradient.addColorStop(0, '#1db85b')
  gradient.addColorStop(1, '#ddbf46')
  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 为每个地点分配坐标
  const coordinates = calculateCoordinates(routePoints.value)

  // 绘制连接线和点
  drawConnections(ctx, coordinates)

  // 绘制地点标签
  drawLocationLabels(ctx, coordinates)
}

// 新增：路径检查相关数据
const startCity = ref('')
const endCity = ref('')
const checkResult = ref<PathCheckResult | null>(null)

// 计算属性：获取所有可用城市
const availableCities = computed(() => {
  const cities = new Set<string>();

  // 从routePoints中获取城市
  routePoints.value.forEach(point => {
    cities.add(point.location);
  });

  return Array.from(cities).sort();
});

// 新增方法：检查路径完整性
const checkRouteIntegrity = () => {
  // 验证城市选择
  const validationError = validateCitySelection(
      startCity.value,
      endCity.value,
      availableCities.value
  );

  if (validationError) {
    ElMessage.warning(validationError);
    return;
  }

  // 调用路径检查算法
  const result = checkPathIntegrity(
      startCity.value,
      endCity.value,
      routeTransports.value
  );

  checkResult.value = result;

  if (result.isComplete) {
    ElMessage.success('路径完整！');
  } else {
    ElMessage.warning('路径不完整!');
  }
}
</script>

<style scoped>
.travel-route-container {
  padding: 30px;
  max-width: 1200px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  min-height: 100vh;
}

.header-section {
  text-align: center;
  margin-bottom: 30px;
}

.header-section h2 {
  color: #303133;
  font-size: 28px;
  margin-bottom: 8px;
  font-weight: 600;
}

.subtitle {
  color: #606266;
  font-size: 14px;
  margin: 0;
}

.controls {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.primary-button {
  padding: 12px 32px;
  background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.primary-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.primary-button:active {
  transform: translateY(0);
}

.button-loading {
  display: flex;
  align-items: center;
  gap: 8px;
}

.route-header {
  text-align: center;
  margin-bottom: 20px;
}

.route-header h3 {
  color: #303133;
  font-size: 22px;
  margin-bottom: 8px;
  font-weight: 600;
}

.route-notice {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.canvas-container {
  border: 1px solid #dcdfe6;
  border-radius: 12px;
  margin: 20px 0;
  overflow: auto;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.cards-container {
  margin-top: 40px;
}

.info-card {
  border-radius: 12px;
  border: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.flight-item, .location-item {
  padding: 12px;
  margin: 8px 0;
  border-radius: 8px;
  background: #f8f9fa;
  transition: background-color 0.3s ease;
}

.flight-item:hover, .location-item:hover {
  background: #e9ecef;
}

.city-highlight {
  color: #409EFF;
  font-weight: 500;
}

.location-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.location-name {
  font-weight: 500;
  color: #303133;
}

.reservation-status {
  display: flex;
  gap: 16px;
  font-size: 14px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-state i {
  font-size: 24px;
  margin-bottom: 12px;
  display: block;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

@media (max-width: 768px) {
  .travel-route-container {
    padding: 20px 15px;
  }

  .header-section h2 {
    font-size: 24px;
  }

  .primary-button {
    padding: 10px 24px;
    font-size: 14px;
  }

  .reservation-status {
    flex-direction: column;
    gap: 8px;
  }

  .canvas-container {
    margin: 15px -10px;
    border-radius: 0;
  }
}

.integrity-check-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.integrity-check-section h3 {
  color: #303133;
  margin-bottom: 15px;
  font-size: 18px;
}

.check-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  margin-bottom: 15px;
}

.select-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.select-group label {
  font-size: 14px;
  color: #606266;
}

.city-select {
  width: 180px;
}

.check-button {
  padding: 10px 20px;
  background: linear-gradient(135deg, #67c23a 0%, #529b2e 100%);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  align-self: flex-end;
  transition: all 0.3s ease;
}

.check-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(103, 194, 58, 0.3);
}

.check-result {
  padding: 15px;
  border-radius: 8px;
  margin-top: 15px;
}

.result-success {
  display: flex;
  flex-direction: column;
  gap: 10px;
  color: #67c23a;
  font-weight: 500;
}

.result-failure {
  display: flex;
  flex-direction: column;
  gap: 10px;
  color: #f56c6c;
  font-weight: 500;
}

.path-details, .missing-flights, .reachable-info {
  margin-left: 25px;
  margin-top: 10px;
  font-weight: normal;
  color: #606266;
}

.path-details p, .missing-flights p, .reachable-info p {
  margin-bottom: 5px;
}

.missing-flights ul {
  margin: 0;
  padding-left: 20px;
}

.missing-flights li {
  margin-bottom: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .check-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .city-select {
    width: 100%;
  }

  .check-button {
    align-self: stretch;
    margin-top: 10px;
  }
}
</style>